﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CDSBDemandControl.Presenter;
using CDSBDemandControl.Model;
using System.Web.UI.HtmlControls;
using System.Drawing;

namespace CDSBDemandControl.View.Web.PaginasInternas
{
    public partial class OldAlocacao : System.Web.UI.Page, IDiscriminatorDemand
    {
        private Presenter.DiscriminatorDemand Presenter;
        public int[] sumarizador;
        public int[] sumarizadorTotal;
        public int[] sumarizadorTotalAtiva;
        public int[] sumarizadorForcaDesenvolvimento;
        public string caption = "Previsão de Alocação referente ao mês {0}.";

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetExpires(DateTime.Now.Subtract(new TimeSpan(24, 0, 0)));
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            if (!this.IsPostBack || this.Session["Presenter"] == null)
            {
                this.Presenter = new DiscriminatorDemand(this);

                this.Session["Presenter"] = this.Presenter;

                if (!this.IsPostBack)
                    this.ListarAlocacao();
            }
            else
            {
                this.Presenter = (Presenter.DiscriminatorDemand)this.Session["Presenter"];
                this.Presenter.ResetView(this);
            }

            if(Session["numberOfFrames"] != null)
                this.GeneratePaginator(Int32.Parse(Session["numberOfFrames"].ToString()));            
            else
                this.ListarAlocacao();
        }

        private void ListarAlocacao()
        {
            this.Presenter.ListarPrevisaoAlocacao();
        }

        public enum listaEstados
        {
            Ativa,
            EmFila,
            EmCodificacao,
            AlterandoArtefatos
        }

        void IDiscriminatorDemand.ExibirAlocacao(IEnumerable<DemandModel> demandModels)
        {
            //Here apply the final data
            demandModels.ToList().ForEach(delegate(DemandModel md)
            {
                if (md.Start.HasValue)
                {
                    md.EstimatedStart = md.Start;
                }
                if (md.Conclude.HasValue)
                {
                    md.EstimatedConclude = md.Conclude;
                }
            });

            Session["demandModels"] = demandModels;
            List<DateTime> feriados = this.Presenter.getFeriados();
            Session["feriados"] = feriados;

            DateTime? dtInicioPeriodo = demandModels.Min(x => x.EstimatedStart);
            DateTime? dtFinalPeriodo = demandModels.Max(x => x.EstimatedConclude);

            DateTime tmStart = new DateTime(dtInicioPeriodo.Value.Year, dtInicioPeriodo.Value.Month, 1);
            DateTime tmEnd = new DateTime(dtFinalPeriodo.Value.Year, dtFinalPeriodo.Value.Month, 1);
            DateTime diff = new DateTime((tmEnd - tmStart).Ticks);

            int numberOfFrames = ((diff.Year - 1) * 12) + diff.Month;

            Session["numberOfFrames"] = numberOfFrames;

            if (Session["comboSelectedMonth"] == null)
            {
                DateTime index = new DateTime((new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1) - tmStart.Date).Ticks);

                this.ProcessarConteudoMensal(tmStart, tmEnd, demandModels, -1 + ((index.Year - 1) * 12) + index.Month, feriados);

                this.ExibirObservacao(string.Format(caption, DateTime.Now.ToString("MMM/yyyy")));

                this.GerarGrafico(tmStart, feriados, -1 + ((index.Year - 1) * 12) + index.Month);

                // Exibe a data da última atualização
                (this.Master.FindControl("LblUltimoUpdate") as Label).Text = "Última atualização em: " + this.Presenter.DemandListLastUpdate.ToShortDateString() + " as " + this.Presenter.DemandListLastUpdate.ToShortTimeString();

                (this.Master.FindControl("txtTimeToCompare") as HtmlGenericControl).InnerHtml =
                    this.Presenter.DemandListLastUpdate.Year + "," +
                    (this.Presenter.DemandListLastUpdate.Month - 1) + "," +
                    this.Presenter.DemandListLastUpdate.Day + "," +
                    this.Presenter.DemandListLastUpdate.Hour + "," +
                    this.Presenter.DemandListLastUpdate.Minute + "," +
                    this.Presenter.DemandListLastUpdate.Second;
            }
            else
            {
                int index = Convert.ToInt32(Session["comboSelectedMonth"]);

                this.ProcessarConteudoMensal(tmStart, tmEnd, demandModels, index, feriados);
                this.ExibirObservacao(string.Format(caption, dtInicioPeriodo.Value.AddMonths(index).ToString("MMM/yyyy")));
                this.GerarGrafico(tmStart, feriados, index);

            }
        }

        private void ProcessarConteudoMensal(DateTime tmStart, DateTime tmEnd, IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels, int index, List<DateTime> feriados)
        {
            tmStart = tmStart.AddMonths(index);

            List<string> teamProjects = new List<string>() { "TeamProjectsSinacor", "TeamProjectsIMercado", "TeamProjectsSiteBVMF" };
            int numberOfCols = System.DateTime.DaysInMonth(tmStart.Year, tmStart.Month);

            sumarizadorTotal = new int[numberOfCols];
            sumarizadorTotalAtiva = new int[numberOfCols];

            foreach (string str in teamProjects)
            {
                var demandGroups =
                       from d in demandModels
                       where    (
                                    this.Presenter.CheckExistsWithin(d.Project, str)
                                    &&
                                    this.inIntervalo(d.EstimatedStart, d.EstimatedConclude, tmStart)
                                    && 
                                    d.State != "Cancelada"
                                )
                                ||
                                (
                                    (d.State == "Cancelada" && d.UsedHours != 0) 
                                    && 
                                    (this.Presenter.CheckExistsWithin(d.Project, str))
                                    &&
                                    (this.inIntervalo(d.EstimatedStart, d.EstimatedConclude, tmStart))
                                )

                       group d by d.Project into g
                       select new { Project = g.Key, Demands = g };

                int subGroups = demandGroups.ToList().Count;

                sumarizador = new int[numberOfCols];

                int counter = demandGroups.ToList().Count;

                this.GerarHeader(counter, str, parentDiv);

                for (int i = 0; i < subGroups; i++)
                {
                    this.CarregarConteudoMensal(demandGroups.ToList()[i].Demands, tmStart, str, feriados);
                    this.parentDiv.Controls.Add(new LiteralControl("<br />"));
                }
                this.GerarTotalModulo(numberOfCols, counter, str, tmStart, feriados);
            }

            GerarHeaderTotal(tmStart);

            GerarTotalGeral(numberOfCols, tmStart, feriados);

            GeraTotalAtiva(numberOfCols, tmStart, feriados);

            GerarTotalDisponibilidade(tmStart, numberOfCols, out sumarizadorForcaDesenvolvimento, feriados);

            GerarTotalDiferenca(sumarizadorTotal, sumarizadorTotalAtiva, sumarizadorForcaDesenvolvimento, numberOfCols, tmStart, feriados);
        }

        private void GeraTotalAtiva(int numberOfCols, DateTime tmStart, List<DateTime> feriados)
        {
            Table tblTT = new Table();

            tblTT.Attributes.Add("cellspacing", "1");
            tblTT.Attributes.Add("cellpadding", "2");
            tblTT.Style.Add("background-color", "#333333");

            TableRow rTT = new TableRow();
            rTT.Style.Add("align", "left");
            rTT.Style.Add("background-color", "#FFCC66");
            rTT.Style.Add("font-family", "Verdana");
            rTT.Style.Add("font-size", "X-Small");

            TableCell cTT = new TableCell();
            cTT.Controls.Add(new LiteralControl("HORAS PLANEJADAS:"));
            cTT.Width = 150;
            rTT.Cells.Add(cTT);

            for (int j = 0; j < numberOfCols; j++)
            {
                cTT = new TableCell();
                cTT.Style.Add("text-align", "center");
                int hours = sumarizadorTotalAtiva[j];

                DateTime collumnDate = tmStart.AddDays(j);
                if ((collumnDate.DayOfWeek == DayOfWeek.Saturday || collumnDate.DayOfWeek == DayOfWeek.Sunday)
                                    || (feriados.Contains(collumnDate.Date)))
                {
                    cTT.Style.Add("background-color", "#FFFFFF");
                }
                else
                {
                    cTT.Controls.Add(new LiteralControl(hours + "h"));
                }
                cTT.Width = 35;
                rTT.Cells.Add(cTT);
            }

            tblTT.Rows.Add(rTT);
            totalGeralDiv.Controls.Add(tblTT);
        }

        private void GerarTotalDiferenca(int[] sumarizadorTotal, int[] sumarizadorTotalAtiva, int[] sumarizadorForcaDesenvolvimento, int numberOfCols, DateTime tmStart, List<DateTime> feriados)
        {
            Table tblTT = new Table();

            tblTT.Attributes.Add("cellspacing", "1");
            tblTT.Attributes.Add("cellpadding", "2");
            tblTT.Style.Add("background-color", "#333333");

            TableRow rTT = new TableRow();
            rTT.Style.Add("align", "left");
            rTT.Style.Add("background-color", "#FFFFFF");
            rTT.Style.Add("font-family", "Verdana");
            rTT.Style.Add("font-size", "X-Small");

            TableCell cTT = new TableCell();
            //cTT.Style.Add("font-weight", "bold");
            cTT.Controls.Add(new LiteralControl("HORAS DISPONIVEIS:"));
            cTT.Width = 150;
            rTT.Cells.Add(cTT);

            for (int j = 0; j < numberOfCols; j++)
            {
                cTT = new TableCell();
                cTT.Style.Add("text-align", "center");

                int hours = ((sumarizadorTotal[j] + sumarizadorTotalAtiva[j]) - (sumarizadorForcaDesenvolvimento[j])) * -1;

                DateTime collumnDate = tmStart.AddDays(j);
                if ((collumnDate.DayOfWeek == DayOfWeek.Saturday || collumnDate.DayOfWeek == DayOfWeek.Sunday)
                                    || (feriados.Contains(collumnDate.Date)))
                {
                    cTT.Style.Add("background-color", "#FFFFFF");
                }
                else
                {
                    cTT.Controls.Add(new LiteralControl(hours + "h"));

                    if (hours >= 0)
                    {
                        cTT.Style.Add("background-color", "#FF3300");//"#33CC33");                        
                    }
                    else
                    {
                        cTT.Style.Add("background-color", "#33CC33");//"#FF3300");                        
                    }
                }

                cTT.Width = 35;
                rTT.Cells.Add(cTT);
            }

            tblTT.Rows.Add(rTT);
            totalGeralDiv.Controls.Add(tblTT);
        }

        private void GerarTotalDisponibilidade(DateTime tmStart, int numberOfCols, out int[] sumarizadorForcaDesenvolvimento, List<DateTime> feriados)
        {
            sumarizadorForcaDesenvolvimento = new int[numberOfCols];

            Table tblTT = new Table();

            tblTT.Attributes.Add("cellspacing", "1");
            tblTT.Attributes.Add("cellpadding", "2");
            tblTT.Style.Add("background-color", "#333333");

            TableRow rTT = new TableRow();
            rTT.Style.Add("align", "left");
            rTT.Style.Add("background-color", "#99CCFF");
            rTT.Style.Add("font-family", "Verdana");
            rTT.Style.Add("font-size", "X-Small");

            TableCell cTT = new TableCell();
            //cTT.Style.Add("font-weight", "bold");
            cTT.Controls.Add(new LiteralControl("FORÇA DESENVOLVIMENTO:"));
            cTT.Width = 150;
            rTT.Cells.Add(cTT);

            List<DeveloperModel> devsCDSB =
                    this.Presenter.Developers.ToList().FindAll(
                    delegate(DeveloperModel md)
                    {
                        bool forTeam = md.DeveloperTeam != "Suporte 3º Nível";
                        bool forMission = (md.Mission == Mission.Developer);
                        bool forCDSB = (md.DeveloperTeam.ToLower().Contains("time"));

                        return (forTeam && forMission && forCDSB);
                    });

            List<DeveloperModel> devs7Comm =
                this.Presenter.Developers.ToList().FindAll(
                delegate(DeveloperModel md)
                {
                    bool forTeam = md.DeveloperTeam != "Suporte 3º Nível";
                    bool forMission = (md.Mission == Mission.Developer);
                    bool forCDSB = (md.DeveloperTeam == "7COMm-VCoding");


                    //HC
                    bool list = (md.DeveloperName != "Ubiratan Radanovic Vieira");

                    return (forTeam && forMission && forCDSB && list);
                });

            for (int j = 0; j < numberOfCols; j++)
            {
                cTT = new TableCell();
                //cTT.Style.Add("font-weight", "bold");
                cTT.Style.Add("text-align", "center");

                DateTime collumnDate = tmStart.AddDays(j);
                if ((collumnDate.DayOfWeek == DayOfWeek.Saturday || collumnDate.DayOfWeek == DayOfWeek.Sunday)
                                    || (feriados.Contains(collumnDate.Date)))
                {
                    cTT.Style.Add("background-color", "#FFFFFF");
                }
                else
                {

                    int hoursCDSB = devsCDSB.FindAll(delegate(DeveloperModel d)
                    {
                        List<DateTime> lstDataInterna = new List<DateTime>();

                        d.Dayof.ForEach(delegate(string strData)
                        {
                            lstDataInterna.Add(DateTime.Parse(strData.Split('|')[0]));
                        });

                        bool porFolga = lstDataInterna.Contains(tmStart.AddDays(j).Date);
                        bool porFerias = (
                            (d.StartFreeDaysPaid.HasValue && d.FinishFreeDaysPaid.HasValue)
                            &&
                            (tmStart.AddDays(j).Date >= d.StartFreeDaysPaid.Value.Date && tmStart.AddDays(j).Date <= d.FinishFreeDaysPaid.Value.Date)
                                            );

                        bool porInicio = false;

                        if (d.DeveloperStartAt.HasValue)
                            porInicio = tmStart.AddDays(j).Date < d.DeveloperStartAt.Value.Date;

                        return (!porFolga && !porFerias && !porInicio);

                    }).Count;

                    int hours7Comm = devs7Comm.FindAll(delegate(DeveloperModel d)
                    {
                        List<DateTime> lstDataInterna = new List<DateTime>();

                        d.Dayof.ForEach(delegate(string strData)
                        {
                            lstDataInterna.Add(DateTime.Parse(strData.Split('|')[0]));
                        });

                        bool porFolga = lstDataInterna.Contains(tmStart.AddDays(j).Date);
                        bool porFerias = (
                            (d.StartFreeDaysPaid.HasValue && d.FinishFreeDaysPaid.HasValue)
                            &&
                            (tmStart.AddDays(j).Date >= d.StartFreeDaysPaid.Value.Date && tmStart.AddDays(j).Date <= d.FinishFreeDaysPaid.Value.Date)
                                            );

                        bool porInicio = false;

                        if (d.DeveloperStartAt.HasValue)
                            porInicio = tmStart.AddDays(j).Date < d.DeveloperStartAt.Value.Date;

                        return (!porFolga && !porFerias && !porInicio);
                    }).Count;

                    hoursCDSB = hoursCDSB * 8;
                    hours7Comm = hours7Comm * 8;

                    string write = "<a title='" + hoursCDSB + " horas disponiveis CDSB / " + hours7Comm + " horas disponiveis 7Comm.'>" + (hoursCDSB + hours7Comm) + "h</a>";

                    sumarizadorForcaDesenvolvimento[j] = (hoursCDSB + hours7Comm);

                    cTT.Controls.Add(new LiteralControl(write));
                }

                cTT.Width = 35;
                rTT.Cells.Add(cTT);
            }

            tblTT.Rows.Add(rTT);
            totalGeralDiv.Controls.Add(tblTT);
        }

        private void GerarHeader(int counter, string str, HtmlGenericControl ctr)
        {
            Table tbl = new Table();
            TableRow r;
            TableCell c;

            if (counter != 0)
            {
                //Header

                r = new TableRow();

                r.Style.Add("background-color", "#FFFFFF");
                r.Style.Add("font-family", "Verdana");
                r.Style.Add("font-size", "Small");

                c = new TableCell();
                c.Style.Add("font-weight", "bold");
                c.Style.Add("text-align", "center");
                c.Controls.Add(new LiteralControl(str));
                r.Cells.Add(c);

                tbl.Rows.Add(r);
                ctr.Controls.Add(tbl);

                //Header
            }
        }

        private void GerarTotalModulo(int numberOfCols, int counter, string str, DateTime tmStart, List<DateTime> feriados)
        {
            //Total Modulo
            if (counter != 0)
            {
                Table tbl = new Table();
                TableRow r;
                TableCell c;

                tbl = new Table();

                tbl.Attributes.Add("cellspacing", "1");
                tbl.Attributes.Add("cellpadding", "2");
                tbl.Style.Add("background-color", "#333333");

                r = new TableRow();
                r.Style.Add("align", "left");
                r.Style.Add("background-color", "#FFFF99");
                r.Style.Add("font-family", "Verdana");
                r.Style.Add("font-size", "X-Small");

                c = new TableCell();
                //c.Style.Add("font-weight", "bold");
                c.Controls.Add(new LiteralControl(str.Replace("TeamProjects", "")));
                c.Width = 150;
                r.Cells.Add(c);

                for (int j = 0; j < numberOfCols; j++)
                {
                    c = new TableCell();
                    c.Style.Add("text-align", "center");

                    DateTime collumnDate = tmStart.AddDays(j);

                    if ((collumnDate.DayOfWeek == DayOfWeek.Saturday || collumnDate.DayOfWeek == DayOfWeek.Sunday)
                                    || (feriados.Contains(collumnDate.Date)))
                    {
                        c.Style.Add("background-color", "#FFFFFF");
                    }
                    else
                    {
                        int hours = sumarizador[j];

                        c.Controls.Add(new LiteralControl(hours + "h"));
                    }

                    c.Width = 35;
                    r.Cells.Add(c);
                }

                tbl.Rows.Add(r);
                parentDiv.Controls.Add(tbl);
                this.parentDiv.Controls.Add(new LiteralControl("<br />"));
            }
        }

        private void GerarTotalGeral(int numberOfCols, DateTime tmStart, List<DateTime> feriados)
        {
            Table tblTT = new Table();

            tblTT.Attributes.Add("cellspacing", "1");
            tblTT.Attributes.Add("cellpadding", "2");
            tblTT.Style.Add("background-color", "#333333");

            TableRow rTT = new TableRow();
            rTT.Style.Add("align", "left");
            rTT.Style.Add("background-color", "#FFFF99");
            rTT.Style.Add("font-family", "Verdana");
            rTT.Style.Add("font-size", "X-Small");

            TableCell cTT = new TableCell();
            //cTT.Style.Add("font-weight", "bold");
            cTT.Controls.Add(new LiteralControl("HORAS ALOCADAS:"));
            cTT.Width = 150;
            rTT.Cells.Add(cTT);

            for (int j = 0; j < numberOfCols; j++)
            {
                cTT = new TableCell();
                cTT.Style.Add("text-align", "center");
                int hours = sumarizadorTotal[j];

                DateTime collumnDate = tmStart.AddDays(j);
                if ((collumnDate.DayOfWeek == DayOfWeek.Saturday || collumnDate.DayOfWeek == DayOfWeek.Sunday)
                                    || (feriados.Contains(collumnDate.Date)))
                {
                    cTT.Style.Add("background-color", "#FFFFFF");
                }
                else
                {
                    cTT.Controls.Add(new LiteralControl(hours + "h"));
                }
                cTT.Width = 35;
                rTT.Cells.Add(cTT);
            }

            tblTT.Rows.Add(rTT);
            totalGeralDiv.Controls.Add(tblTT);
        }


        private void GerarHeaderTotal(DateTime tmStart)
        {
            int numberOfCols = System.DateTime.DaysInMonth(tmStart.Year, tmStart.Month);

            Table tbl = new Table();
            TableRow r;
            TableCell c;

            tbl.Attributes.Add("cellspacing", "1");
            tbl.Attributes.Add("cellpadding", "2");
            tbl.Style.Add("background-color", "#333333");

            r = new TableRow();

            r.Style.Add("background-color", "#FFFFFF");
            r.Style.Add("font-family", "Verdana");
            r.Style.Add("font-size", "X-Small");

            for (int j = 0; j <= numberOfCols; j++)
            {

                r.Style.Add("align", "left");
                r.Style.Add("background-color", "#CFCFCF");
                r.Style.Add("font-family", "Verdana");
                r.Style.Add("font-size", "X-Small");

                if (j == 0)
                {
                    c = new TableCell();
                    c.Style.Add("font-weight", "bold");
                    c.Controls.Add(new LiteralControl("DIA:"));
                    c.Width = 150;
                    r.Cells.Add(c);
                }
                else
                {
                    c = new TableCell();
                    c.Style.Add("font-weight", "bold");
                    c.Style.Add("text-align", "center");
                    string dia = tmStart.AddDays(j - 1).Day.ToString();
                    c.Controls.Add(new LiteralControl(dia));
                    c.Width = 35;
                    r.Cells.Add(c);
                }

            }
            tbl.Rows.Add(r);
            totalGeralDiv.Controls.Add(tbl);
        }

        private void CarregarConteudoMensal(IEnumerable<DemandModel> col, DateTime tmStart, string TeamProject, List<DateTime> feriados)
        {
            List<DemandModel> lst = col.ToList();
            string Modulo = lst.First(delegate(DemandModel d) { return true; }).Project;
            int numberOfCols = System.DateTime.DaysInMonth(tmStart.Year, tmStart.Month);
            int numberOfRows = lst.Count;

            Table tbl = new Table();
            TableRow r;
            TableCell c;

            tbl.Attributes.Add("cellspacing", "1");
            tbl.Attributes.Add("cellpadding", "2");
            tbl.Style.Add("background-color", "#333333");

            for (int i = -1; i <= numberOfRows; i++)
            {
                r = new TableRow();

                r.Style.Add("background-color", "#FFFFFF");
                r.Style.Add("font-family", "Verdana");
                r.Style.Add("font-size", "X-Small");
                for (int j = 0; j <= numberOfCols; j++)
                {
                    if (i < 0)
                    {
                        r.Style.Add("align", "left");
                        r.Style.Add("background-color", "#CFCFCF");
                        r.Style.Add("font-family", "Verdana");
                        r.Style.Add("font-size", "X-Small");

                        if (j == 0)
                        {
                            c = new TableCell();
                            c.Style.Add("font-weight", "bold");
                            c.Controls.Add(new LiteralControl(Modulo));
                            c.Width = 150;
                            r.Cells.Add(c);
                        }
                        else
                        {
                            c = new TableCell();
                            c.Style.Add("font-weight", "bold");
                            c.Style.Add("text-align", "center");
                            string dia = tmStart.AddDays(j - 1).Day.ToString();
                            //string Mes = tmStart.AddDays(j - 1).Month.ToString();
                            c.Controls.Add(new LiteralControl(dia));
                            c.Width = 35;
                            r.Cells.Add(c);
                        }
                    }
                    else
                    {
                        if (i != numberOfRows)
                        {
                            if (j == 0)
                            {
                                c = new TableCell();
                                string TaskId = "<a title='" + lst[i].Title + "'>" + lst[i].ID + "</a>";
                                c.Controls.Add(new LiteralControl(TaskId));
                                r.Cells.Add(c);
                            }
                            else
                            {
                                c = new TableCell();
                                c.Style.Add("text-align", "center");
                                DateTime collumnDate = tmStart.AddDays(j - 1);

                                if ((collumnDate.DayOfWeek == DayOfWeek.Saturday || collumnDate.DayOfWeek == DayOfWeek.Sunday)
                                    || (feriados.Contains(collumnDate.Date)))
                                {
                                    c = new TableCell();
                                    c.Style.Add("background-color", "#FFFFFF");
                                }
                                else
                                {
                                    //int days = (int)(lst[i].EstimatedHours / 8);
                                    if ((lst[i].EstimatedStart.Value.Date == collumnDate.Date)
                                        ||
                                    (collumnDate.Date <= lst[i].EstimatedConclude.Value.Date && collumnDate.Date >= lst[i].EstimatedStart.Value.Date))
                                    {
                                        if (lst[i].State == "Ativa")
                                        {
                                            c.Controls.Add(new LiteralControl("8h"));
                                            c.Controls.Add(new LiteralControl("<div id='divInvisible' style='display:none;'>anycontent</div>"));

                                        }
                                        else
                                        {
                                            c.Controls.Add(new LiteralControl("8h"));                                            
                                        }
                                    }
                                }

                                r.Cells.Add(c);
                            }
                        }
                        else
                        {
                            //i == numberOfRows
                            //Totalizar
                            if (j == 0)
                            {
                                r.Style.Add("align", "left");
                                r.Style.Add("background-color", "#FFFF99");
                                r.Style.Add("font-family", "Verdana");
                                r.Style.Add("font-size", "X-Small");

                                c = new TableCell();
                                c.Style.Add("font-weight", "bold");
                                c.Controls.Add(new LiteralControl("Total:"));
                                r.Cells.Add(c);
                            }
                            else
                            {
                                c = new TableCell();
                                c.Style.Add("text-align", "center");

                                int counter = 0;
                                int counterAtiva = 0;

                                DateTime collumnDate = tmStart.AddDays(j - 1);

                                if ((collumnDate.DayOfWeek == DayOfWeek.Saturday || collumnDate.DayOfWeek == DayOfWeek.Sunday)
                                    || (feriados.Contains(collumnDate.Date)))
                                {
                                    c = new TableCell();
                                    c.Style.Add("background-color", "#FFFFFF");
                                }
                                else
                                {
                                    foreach (TableRow row in tbl.Rows)
                                    {
                                        if (row.Cells[j].Controls.Count == 1)
                                        {
                                            counter++;
                                        }
                                        else
                                            if (row.Cells[j].Controls.Count > 1)
                                            {
                                                //counter++;
                                                if (((System.Web.UI.LiteralControl)(row.Cells[j].Controls[1])).Text == "<div id='divInvisible' style='display:none;'>anycontent</div>")
                                                    counterAtiva++;
                                            }
                                    }

                                    c.Controls.Add(new LiteralControl(""+ (((counter - 1) * 8) + (counterAtiva * 8)) + "h"));
                                }

                                r.Cells.Add(c);
                                
                                sumarizador[j - 1] += ((counter - 1) * 8);
                                sumarizador[j - 1] += (counterAtiva * 8);

                                sumarizadorTotal[j - 1] += ((counter - 1) * 8);
                                sumarizadorTotalAtiva[j - 1] += (counterAtiva * 8);

                            }
                        }
                    }
                }
                tbl.Rows.Add(r);
            }
            parentDiv.Controls.Add(tbl);
        }

        private bool inIntervalo(DateTime? EstimatedStart, DateTime? EstimatedConclude, DateTime tmStart)
        {
            //inicio
            bool porInicio =
                (EstimatedStart.Value.Date <= tmStart.Date && EstimatedConclude.Value.Date >= tmStart.Date);

            //final
            bool porFinal =
                (EstimatedStart.Value.Date >= tmStart.Date && tmStart.Month == EstimatedStart.Value.Month);

            return (porInicio || porFinal);
        }

        private void GerarGrafico(DateTime tmStart, List<DateTime> feriados, int index)
        {
            tmStart = tmStart.AddMonths(index);

            List<string> lines = new List<string>() { "Alocacao", "ForcaDesenvolvimento" };

            for (int i = 0; i < 2; i++)
            {
                chartAlocDisp.Series.Add(lines[i]);
                chartAlocDisp.Series[lines[i]].ChartArea = "MainChart";
                chartAlocDisp.Series[lines[i]].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Line;

                for (int j = 0; j < sumarizadorTotal.Length; j++)
                {
                    DateTime collumnDate = tmStart.AddDays(j);

                    System.Web.UI.DataVisualization.Charting.DataPoint dt;
                    if (i == 0)
                    {
                        chartAlocDisp.Series[lines[i]].Color = Color.Blue;
                        dt = new System.Web.UI.DataVisualization.Charting.DataPoint(j + 1, sumarizadorTotal[j] + sumarizadorTotalAtiva[j]);
                        if (j == 0 || j % 2 == 0) dt.Label = (sumarizadorTotal[j] + sumarizadorTotalAtiva[j]) + "h";
                        if ((collumnDate.DayOfWeek != DayOfWeek.Saturday && collumnDate.DayOfWeek != DayOfWeek.Sunday)
                                    && (!feriados.Contains(collumnDate.Date)))
                            chartAlocDisp.Series[lines[i]].Points.Add(dt);
                    }
                    else
                    {
                        chartAlocDisp.Series[lines[i]].Color = Color.Red;
                        dt = new System.Web.UI.DataVisualization.Charting.DataPoint(j + 1, sumarizadorForcaDesenvolvimento[j]);
                        if (j == 0 || j % 2 == 0) dt.Label = sumarizadorForcaDesenvolvimento[j] + "h";
                        if ((collumnDate.DayOfWeek != DayOfWeek.Saturday && collumnDate.DayOfWeek != DayOfWeek.Sunday)
                                    && (!feriados.Contains(collumnDate.Date)))
                            chartAlocDisp.Series[lines[i]].Points.Add(dt);
                    }
                }

            }
        }

        public void GeneratePaginator(int totalPages)
        {
            if (cboMonths.Items.Count == 0)
            {
                DateTime? dtInicioPeriodo = ((IEnumerable<DemandModel>)Session["demandModels"]).Min(x => x.EstimatedStart);
                DateTime tmStart = new DateTime(dtInicioPeriodo.Value.Year, dtInicioPeriodo.Value.Month, 1);
                int selectedIndex = 0;

                for (int i = 0; i < totalPages; i++)
                {
                    cboMonths.Items.Add(tmStart.AddMonths(i).Month + "/" + tmStart.AddMonths(i).Year);
                    if (tmStart.AddMonths(i).Year == DateTime.Now.Year && tmStart.AddMonths(i).Month == DateTime.Now.Month)
                        selectedIndex = i;
                }

                cboMonths.Items.Add("Relatório Anual");

                if (Session["comboSelectedMonth"] == null)
                    cboMonths.SelectedIndex = selectedIndex;
                else
                    cboMonths.SelectedIndex = Convert.ToInt32(Session["comboSelectedMonth"]);
            }
        }

        private void ExibirObservacao(string obs)
        {
            this.LblObsOrdenacao.Text = obs;
            this.LblObsOrdenacao.Visible = this.LblObsOrdenacao.Text.Length > 0 ? true : false;
        }

        protected void cboMonths_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index;
            if ((index = (cboMonths.SelectedIndex)) == (cboMonths.Items.Count - 1))
            {
                Response.Redirect("AlocacaoAnual.aspx");
            }
            else
            {
                IEnumerable<DemandModel> demandModels = (IEnumerable<DemandModel>)Session["demandModels"];
                List<DateTime> feriados = (List<DateTime>)Session["feriados"];
                
                DateTime? dtInicioPeriodo = demandModels.Min(x => x.EstimatedStart);
                DateTime? dtFinalPeriodo = demandModels.Max(x => x.EstimatedConclude);

                DateTime tmStart = new DateTime(dtInicioPeriodo.Value.Year, dtInicioPeriodo.Value.Month, 1);
                DateTime tmEnd = new DateTime(dtFinalPeriodo.Value.Year, dtFinalPeriodo.Value.Month, 1);
                DateTime diff = new DateTime((tmEnd - tmStart).Ticks);

                int numberOfFrames = ((diff.Year - 1) * 12) + diff.Month;

                Session["numberOfFrames"] = numberOfFrames;

                this.ProcessarConteudoMensal(tmStart, tmEnd, demandModels, index, feriados);
                this.ExibirObservacao(string.Format(caption, dtInicioPeriodo.Value.AddMonths(index).ToString("MMM/yyyy")));

                this.GerarGrafico(tmStart, feriados, index);
            }

        }

        #region IDiscriminatorDemand Members

        void IDiscriminatorDemand.ExibirFila(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirEsteira(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirRanking(IEnumerable<CDSBDemandControl.Model.DeveloperModel> developers, IEnumerable<CDSBDemandControl.Model.DeveloperModel> leaders, IEnumerable<CDSBDemandControl.Model.DeveloperModel> focalpoints)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirAtrasos(IEnumerable<CDSBDemandControl.Model.DemandModel> PendingDemands, IEnumerable<CDSBDemandControl.Model.DemandModel> Concludeddemands)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFaturamento(List<CDSBDemandControl.Model.BillingModel> billing, bool canSeeBilling)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirScenariosAndTasks(List<CDSBDemandControl.Model.ScenarioModel> scenarios)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirCodeReview(IEnumerable<CDSBDemandControl.Model.DemandModel> WorkItemsWithCodeReview, IEnumerable<CDSBDemandControl.Model.DemandModel> WorkItemsWithoutCodeReview)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirBugsdeProducao(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirListaDisp(IEnumerable<CDSBDemandControl.Model.DemandModel> list, IEnumerable<CDSBDemandControl.Model.DeveloperModel> modelAusencias, List<DateTime> fer)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirBugsdeProducaoUltimoMes(List<CDSBDemandControl.Model.DemandModel> BugList)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFactoryWaitingList(List<CDSBDemandControl.Model.BillingModel> Billing, bool AllowsShow)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFactoryProductionList(List<BillingModel> billing, bool canSeeBilling)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirSolicitacoesSites(List<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirManagementTeamTasks(List<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        #endregion

    }
}
